<{include file="v2/header.html"}>
<main class="pt-24 pb-16">
    <!-- 页面标题 -->
    <section class="container mx-auto px-4 mb-12">
        <div class="flex flex-col md:flex-row md:items-end justify-between">
            <div>
                <h1 class="text-[clamp(1.8rem,4vw,2.8rem)] font-song font-bold mb-2 scroll-reveal">典籍</h1>
                <p class="text-lightink max-w-2xl scroll-reveal">探索传世经典文集，感受中华文化的深厚底蕴</p>
            </div>
            
            <div class="mt-6 md:mt-0 flex items-center space-x-4 scroll-reveal">
                <div class="relative">
                    <input type="text" id="search-input" placeholder="搜索典籍..." class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-cinnabar focus:border-transparent w-full md:w-64">

                    <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-lightink"></i>
                </div>
            </div>
        </div>
    </section>
    
    <!-- 筛选区域 -->
    <section class="container mx-auto px-4 mb-12">
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
            <div class="lg:col-span-1 scroll-reveal">
                <div class="bg-paper rounded-xl p-6 shadow-sm sticky top-24">
                    <h3 class="font-song font-bold text-lg mb-6 pb-3 border-b border-gray-200">筛选条件</h3>
                    
                    <!-- 朝代筛选 -->
                    <div class="mb-6">
                        <h4 class="font-medium mb-3">朝代</h4>
                        <div class="flex flex-wrap gap-2 filter-buttons">
                            <button class="filter-tag-active px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="dynasty" data-value="all">全部</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="dynasty" data-value="唐">唐</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="dynasty" data-value="宋">宋</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="dynasty" data-value="元">元</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="dynasty" data-value="明">明</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="dynasty" data-value="清">清</button>
                        </div>
                    </div>
                    
                    <!-- 类型筛选 -->
                    <div class="mb-6">
                        <h4 class="font-medium mb-3">类型</h4>
                        <div class="flex flex-wrap gap-2 filter-buttons">
                            <button class="filter-tag-active px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="type" data-value="all">全部</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="type" data-value="诗集">诗集</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="type" data-value="词集">词集</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="type" data-value="文集">文集</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="type" data-value="曲选">曲选</button>
                        </div>
                    </div>
                    
                    <!-- 篇幅筛选 -->
                    <div class="mb-6">
                        <h4 class="font-medium mb-3">篇幅</h4>
                        <div class="flex flex-wrap gap-2 filter-buttons">
                            <button class="filter-tag-active px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="length" data-value="all">全部</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="length" data-value="精选本">精选本</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="length" data-value="全本">全本</button>
                            <button class="bg-rice hover:bg-gray-200 px-4 py-2 rounded-full text-sm transition-all duration-300" data-filter="length" data-value="选注本">选注本</button>
                        </div>
                    </div>
                    
                    <!-- 重置筛选 -->
                    <button id="reset-filter" class="w-full border border-gray-300 text-lightink px-4 py-2 rounded-lg hover:bg-gray-100 transition-colors">
                        重置筛选
                    </button>
                </div>
            </div>
            
            <div class="lg:col-span-3">
                <!-- 典籍列表 -->
                <div id="classic-list" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 典籍列表将通过JS动态生成 -->
                </div>
                
                <!-- 加载更多 -->
                <div class="text-center mt-12 scroll-reveal">
                    <button id="load-more" class="border-2 border-ink text-ink px-8 py-3 rounded-full hover:bg-ink hover:text-rice transition-all duration-300 font-song">
                        加载更多 <i class="fa fa-refresh ml-2"></i>
                    </button>
                </div>
            </div>
        </div>
    </section>
</main>
<!-- JavaScript -->
<script>
// 筛选条件
const filterParams = {
    dynasty: 'all',
    type: 'all',
    length: 'all',
    page: 1,
    search: ''
};

// 页面加载时获取初始数据
$(document).ready(function() {
    fetchClassicList();
    
    // 筛选标签切换
    $('.filter-buttons .filter-tag-active, .filter-buttons .bg-rice').click(function() {
        const $this = $(this);
        const filterType = $this.data('filter');
        const filterValue = $this.data('value');
        
        // 只在同级筛选标签中切换状态
        $this.parent().find('button').removeClass('filter-tag-active').addClass('bg-rice hover:bg-gray-200');
        $this.removeClass('bg-rice hover:bg-gray-200').addClass('filter-tag-active');
        
        // 更新筛选参数并重新加载数据
        filterParams[filterType] = filterValue;
        filterParams.page = 1;
        fetchClassicList(true);
    });
    
    // 搜索框事件修正
    $('#search-input').on('input', function() {
        const searchValue = $(this).val().trim();
        filterParams.search = searchValue;
        filterParams.page = 1;
        
        // 避免在输入时添加错误的样式类
        clearTimeout($(this).data('searchTimeout'));
        $(this).data('searchTimeout', setTimeout(() => {
            fetchClassicList(true);
        }, 500)); // 增加延迟，避免频繁请求
    });
    
    // 重置筛选
    // 重置筛选（替换原代码）
    $('#reset-filter').click(function(e) {
        e.stopPropagation(); // 阻止事件冒泡到父元素
        
        // 1. 重置筛选参数
        filterParams.dynasty = 'all';
        filterParams.type = 'all';
        filterParams.length = 'all';
        filterParams.page = 1;
        filterParams.search = '';
        
        // 2. 重置搜索输入框
        const $searchInput = $('input[placeholder="搜索典籍..."]');
        $searchInput.val('');
        
        // 3. 重置所有筛选按钮状态（关键修复）
        // 朝代筛选重置
        $('[data-filter="dynasty"]').removeClass('filter-tag-active').addClass('bg-rice hover:bg-gray-200');
        $('[data-filter="dynasty"][data-value="all"]').removeClass('bg-rice hover:bg-gray-200').addClass('filter-tag-active');
        
        // 类型筛选重置
        $('[data-filter="type"]').removeClass('filter-tag-active').addClass('bg-rice hover:bg-gray-200');
        $('[data-filter="type"][data-value="all"]').removeClass('bg-rice hover:bg-gray-200').addClass('filter-tag-active');
        
        // 篇幅筛选重置
        $('[data-filter="length"]').removeClass('filter-tag-active').addClass('bg-rice hover:bg-gray-200');
        $('[data-filter="length"][data-value="all"]').removeClass('bg-rice hover:bg-gray-200').addClass('filter-tag-active');
        
        // 4. 重新加载数据
        fetchClassicList(true);
    });
    
    // 加载更多
    $('#load-more').click(function() {
        filterParams.page++;
        fetchClassicList(false);
    });
});

/**
 * 获取典籍列表数据
 * @param {boolean} replace 是否替换现有列表（true）或追加（false）
 */
function fetchClassicList(replace = true) {
    // 显示加载状态
    $('#load-more').html('加载中... <i class="fa fa-spinner fa-spin ml-2"></i>').prop('disabled', true);
    
    // 构建查询参数
    const queryParams = new URLSearchParams({
        c: 'main',
        a: 'getClassicList',
        dynasty: filterParams.dynasty,
        type: filterParams.type,
        length: filterParams.length,
        page: filterParams.page,
        search: filterParams.search
    });
    
    // 发起请求
    fetch(`index.php?${queryParams.toString()}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            // 恢复加载更多按钮状态
            $('#load-more').html('加载更多 <i class="fa fa-refresh ml-2"></i>').prop('disabled', false);
            
            if (data.success && data.data && data.data.length > 0) {
                // 渲染典籍列表
                renderClassicList(data.data, replace);
                
                // 如果是最后一页，隐藏加载更多按钮
                if (data.isLastPage) {
                    $('#load-more').hide();
                } else {
                    $('#load-more').show();
                }
            } else {
                // 没有数据时显示提示
                if (replace) {
                    $('#classic-list').html(`
                        <div class="col-span-full text-center py-12">
                            <p class="text-lightink">没有找到符合条件的典籍</p>
                        </div>
                    `);
                }
                $('#load-more').hide();
            }
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            $('#load-more').html('加载失败，重试 <i class="fa fa-refresh ml-2"></i>').prop('disabled', false);
            
            // 显示错误提示
            if (replace) {
                $('#classic-list').html(`
                    <div class="col-span-full text-center py-12">
                        <p class="text-lightink">数据加载失败，请稍后重试</p>
                    </div>
                `);
            }
        });
}

/**
 * 渲染典籍列表
 * @param {Array} classics 典籍数据数组
 * @param {boolean} replace 是否替换现有列表
 */
function renderClassicList(classics, replace = true) {
    const listContainer = $('#classic-list');
    let html = '';
    
    // 如果是替换模式，先清空容器
    if (replace) {
        listContainer.empty();
    }
    
    // 生成列表HTML
    classics.forEach(classic => {
        html += `
        <a href="index.php?c=main&a=classicDetail&id=${classic.id}" class="bg-paper rounded-xl overflow-hidden shadow-sm classic-card-hover scroll-reveal">

            <div class="relative h-48 overflow-hidden">
                <img src="${classic.cover || 'https://picsum.photos/id/24/600/400'}" alt="${classic.title}" class="w-full h-full object-cover transition-transform duration-700 hover:scale-110">
                <div class="absolute top-3 left-3 bg-cinnabar text-rice text-sm px-3 py-1 rounded-full">${classic.type}</div>
            </div>
            <div class="p-6">
                <h3 class="text-xl font-song font-bold mb-2">${classic.title}</h3>
                <p class="text-sm text-lightink mb-3">${classic.author} · ${classic.dynasty}</p>
                <p class="text-ink/80 text-sm mb-4">${classic.description}</p>
                <div class="flex justify-between items-center">
                    <span class="text-xs bg-gray-100 px-2 py-1 rounded-full">${classic.dynasty}</span>
                    <button class="text-cinnabar hover:text-cinnabar/80 transition-colors text-sm">
                        查看详情 <i class="fa fa-angle-right ml-1"></i>
                    </button>
                </div>
            </div>
        </a>
        `;
    });
    
    // 添加到容器中
    listContainer.append(html);
}
</script>
<{include file="v2/footer.html"}>